/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package com.gzx.plugin.tjzy.modular.repaymentQuery.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fhs.trans.service.impl.TransService;
import com.gzx.plugin.tjzy.modular.gzxcase.entity.GzxCase;
import com.gzx.plugin.tjzy.modular.gzxcase.entity.GzxCaseDetail;
import com.gzx.plugin.tjzy.modular.gzxcase.service.GzxCaseDbService;
import com.gzx.plugin.tjzy.modular.repaymentQuery.entity.DataWxjkHksj;
import com.gzx.plugin.tjzy.modular.repaymentQuery.entity.vo.DataWxjkHksjVo;
import com.gzx.plugin.tjzy.modular.repaymentQuery.mapper.DataWxjkHksjMapper;
import com.gzx.plugin.tjzy.modular.repaymentQuery.param.DataWxjkHksjAddParam;
import com.gzx.plugin.tjzy.modular.repaymentQuery.param.DataWxjkHksjEditParam;
import com.gzx.plugin.tjzy.modular.repaymentQuery.param.DataWxjkHksjIdParam;
import com.gzx.plugin.tjzy.modular.repaymentQuery.param.DataWxjkHksjPageParam;
import com.gzx.plugin.tjzy.modular.repaymentQuery.service.DataWxjkHksjService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.common.util.CommonCryptogramUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 维信金科还款数据Service接口实现类
 *
 * @author 刘志刚
 * @date 2024/12/18 09:52
 **/
@Slf4j
@RequiredArgsConstructor
@Service
public class DataWxjkHksjServiceImpl extends ServiceImpl<DataWxjkHksjMapper, DataWxjkHksj> implements DataWxjkHksjService {

    private final GzxCaseDbService caseDbService;

    private final DataWxjkHksjMapper dataWxjkHksjMapper;

    private final TransService transService;

    @Override
    @DS("data")
    public Page<DataWxjkHksjVo> page(DataWxjkHksjPageParam dataWxjkHksjPageParam) {
        QueryWrapper<DataWxjkHksj> queryWrapper = new QueryWrapper<DataWxjkHksj>().checkSqlInjection();
        if (ObjectUtil.isNotEmpty(dataWxjkHksjPageParam.getBusinessId())) {
            queryWrapper.lambda().like(DataWxjkHksj::getBusinessId, dataWxjkHksjPageParam.getBusinessId());
        }
        if (ObjectUtil.isNotEmpty(dataWxjkHksjPageParam.getStartCreateTime()) && ObjectUtil.isNotEmpty(dataWxjkHksjPageParam.getEndCreateTime())) {
            dataWxjkHksjPageParam.setEndCreateTime(dataWxjkHksjPageParam.getEndCreateTime().substring(0, 10) + " 23:59:59");
            dataWxjkHksjPageParam.setStartCreateTime(dataWxjkHksjPageParam.getStartCreateTime().substring(0, 10) + " 00:00:00");
            queryWrapper.lambda().between(DataWxjkHksj::getCreateTime, dataWxjkHksjPageParam.getStartCreateTime(), dataWxjkHksjPageParam.getEndCreateTime());
        }
        if (ObjectUtil.isAllNotEmpty(dataWxjkHksjPageParam.getSortField(), dataWxjkHksjPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(dataWxjkHksjPageParam.getSortOrder());
            queryWrapper.orderBy(true, dataWxjkHksjPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(dataWxjkHksjPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByDesc(DataWxjkHksj::getId);
        }
        Page<DataWxjkHksjVo> dataWxjkHksjVoIPage = dataWxjkHksjMapper.selectVoPage(CommonPageRequest.defaultPage(), queryWrapper);
        setCaseInfo(dataWxjkHksjVoIPage.getRecords());
        return dataWxjkHksjVoIPage;
    }

    @Override
    @DS("data")
    public List<DataWxjkHksjVo> export(DataWxjkHksjPageParam dataWxjkHksjPageParam) {
        LambdaQueryWrapper<DataWxjkHksj> queryWrapper = new LambdaQueryWrapper<>();
        if (ObjectUtil.isNotEmpty(dataWxjkHksjPageParam.getBusinessId())) {
            queryWrapper.like(DataWxjkHksj::getBusinessId, dataWxjkHksjPageParam.getBusinessId());
        }
        if (ObjectUtil.isNotEmpty(dataWxjkHksjPageParam.getStartCreateTime()) && ObjectUtil.isNotEmpty(dataWxjkHksjPageParam.getEndCreateTime())) {
            dataWxjkHksjPageParam.setEndCreateTime(dataWxjkHksjPageParam.getEndCreateTime().substring(0, 10) + " 23:59:59");
            dataWxjkHksjPageParam.setStartCreateTime(dataWxjkHksjPageParam.getStartCreateTime().substring(0, 10) + " 00:00:00");
            queryWrapper.between(DataWxjkHksj::getCreateTime, dataWxjkHksjPageParam.getStartCreateTime(), dataWxjkHksjPageParam.getEndCreateTime());
        }
        queryWrapper.orderByDesc(DataWxjkHksj::getId);
        List<DataWxjkHksjVo> dataWxjkHksjVo = dataWxjkHksjMapper.selectVoList(queryWrapper);
        setCaseInfo(dataWxjkHksjVo);
        transService.transMore(dataWxjkHksjVo);
        return dataWxjkHksjVo;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(DataWxjkHksjAddParam dataWxjkHksjAddParam) {
        DataWxjkHksj dataWxjkHksj = BeanUtil.toBean(dataWxjkHksjAddParam, DataWxjkHksj.class);
        this.save(dataWxjkHksj);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(DataWxjkHksjEditParam dataWxjkHksjEditParam) {
        // DataWxjkHksj dataWxjkHksj = this.queryEntity(dataWxjkHksjEditParam.getId());
        DataWxjkHksj dataWxjkHksj = this.queryEntity(dataWxjkHksjEditParam.getId().toString());
        BeanUtil.copyProperties(dataWxjkHksjEditParam, dataWxjkHksj);
        this.updateById(dataWxjkHksj);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<DataWxjkHksjIdParam> dataWxjkHksjIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(dataWxjkHksjIdParamList, DataWxjkHksjIdParam::getId));
    }

    @Override
    public DataWxjkHksj detail(DataWxjkHksjIdParam dataWxjkHksjIdParam) {
        return this.queryEntity(dataWxjkHksjIdParam.getId().toString());
    }

    @Override
    public DataWxjkHksj queryEntity(String id) {
        DataWxjkHksj dataWxjkHksj = this.getById(id);
        if (ObjectUtil.isEmpty(dataWxjkHksj)) {
            throw new CommonException("维信金科还款数据不存在，id值为：{}", id);
        }
        return dataWxjkHksj;
    }

    private void setCaseInfo(List<DataWxjkHksjVo> hksjVoList) {
        if (CollectionUtil.isNotEmpty(hksjVoList)) {
            //获取getBusinessId
            Set<String> businessIdList = hksjVoList.stream().map(DataWxjkHksjVo::getBusinessId).collect(Collectors.toSet());
            //在detail内找到身份证号
            List<GzxCaseDetail> caseDetailList = new ArrayList<>();
            if (CollectionUtil.isNotEmpty(businessIdList)) {
                caseDetailList = caseDbService.selectCaseDetailList(Wrappers.<GzxCaseDetail>lambdaQuery()
                        .select(GzxCaseDetail::getPartnerBusinessId, GzxCaseDetail::getDebtorCardId)
                        .in(GzxCaseDetail::getPartnerBusinessId, businessIdList));
            }
            //进行businessIdMap
            Map<String, String> businessIdMap = caseDetailList.stream().collect(Collectors.toMap(GzxCaseDetail::getPartnerBusinessId, s -> CommonCryptogramUtil.doSm1AesEncrypt(s.getDebtorCardId()), (oldValue, newValue) -> newValue));
            //根据身份证号查询case
            List<GzxCase> caseList = new ArrayList<>();
            if (CollectionUtil.isNotEmpty(businessIdMap.values())) {
                caseList = caseDbService.selectCaseList(Wrappers.<GzxCase>lambdaQuery()
                        .in(GzxCase::getDebtorCardId, businessIdMap.values()));
            }
            //加密后的身份证号和case
            Map<String, GzxCase> caseMap = caseList.stream().collect(Collectors.toMap(
                    gzxCase -> CommonCryptogramUtil.doSm1AesEncrypt(gzxCase.getDebtorCardId()),
                    Function.identity(),
                    (oldValue, newValue) -> oldValue.getId() > newValue.getId() ? oldValue : newValue
            ));
            //
            for (DataWxjkHksjVo dataWxjkHksjVo : hksjVoList) {
                String businessId = dataWxjkHksjVo.getBusinessId();
                if (businessIdMap.containsKey(businessId)) {
                    String idCard = businessIdMap.get(businessId);
                    if (caseMap.containsKey(idCard)) {
                        GzxCase gzxCase = caseMap.get(idCard);
                        dataWxjkHksjVo.setSeatName(gzxCase.getMediatorName());
                        dataWxjkHksjVo.setAffiliatedCompany(gzxCase.getAffiliatedCompany());
                    }
                }
            }
        }
    }
}
